package com.bookstore.client.user.service.impl;

import java.util.Iterator;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bookstore.client.user.dao.IUserDao;
import com.bookstore.client.user.service.IUserService;
import com.bookstore.commons.beans.Order;
import com.bookstore.commons.beans.OrderItem;
import com.bookstore.commons.beans.User;
import com.bookstore.utils.MailUtils;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

	@Autowired
	private IUserDao userDao;
	
	@Override
	public User findEmail(String email) {
		return userDao.selectEmail(email);
	}

	@Override
	public int addUser(User user,HttpServletRequest request) {
		String emailMsg = "欢迎注册网上书城！请点击激活后使用，<a href='http://localhost:8080"+request.getContextPath()+
				"/client/user/activeUser.do?activeCode="+user.getActiveCode()+"'>激活</a>";
		try {
			MailUtils.sendMail(user.getEmail(),emailMsg);
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return userDao.insertUser(user);
	}

	@Override
	public int activeUser(String activeCode) {
		return userDao.updateUserByActiveCode(activeCode);
	}

	@Override
	public User findUserByUsername(User user) {
		return userDao.selectUserByUsername(user);
	}

	@Override
	public int modifyUser(User user) {
		return userDao.updateUser(user);
	}

	@Override
	public List<Order> findOrderByUser(Integer id) {
		return userDao.selectOrdersByUser(id);
	}

	@Override
	public List<OrderItem> findOrderItemByid(String id) {
		
		return userDao.selectOrderItemById(id);
	}

	@Override
	public void deleteOrder(String id, String flag) {

		if("1".equals(flag)){
			userDao.deleteOrder(id);
			userDao.deletrOrderItem(id);
		}else{
			userDao.deleteOrder(id);
			List<OrderItem> items = userDao.selectOrderItemById(id);
			for (OrderItem orderItem : items) {
				userDao.updateProductById(orderItem);
			}
			
		}
	}
	
	
	

}
